﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Petaframe.DataAccess
{
    public class SqlDeleteCommandBuilder : SqlCommandStringBuilderBase, ISqlCommandStringBuilder
    {
     
       
        public ISqlCommandStringBuilder CommandString(string text)
        {
            _sqlQuery.Append(text);
            return this;
        }

        public ISqlCommandStringBuilder CommandString(TableInfo table)
        {
            if (!table.HasPrimaryKey)
                throw new InvalidOperationException("Tabloda primarykey olmadan delete işlemi yapılamaz!!!");

            _sqlQuery.AppendFormat("delete from {0} where ", table.TableName);


            bool andNeeded = false;
          
            foreach (var item in table.Properties)
            {
                if (item.PrimaryKey)
                {
                    if (andNeeded)
                        _sqlQuery.Append(" and ");

                    _sqlQuery.AppendFormat("{0}={1}", item.PropertyName, table.Parameters[item.PropertyName].DbParameter.ParameterName);
                    andNeeded = true;                   
                }

            }

            return this;
        }

        /// <summary>
        /// Oluşturulan sql komutunu döndürür.
        /// </summary>
        /// <returns>Sql command string</returns>
        public string ToSqlCommandString()
        {
            return _sqlQuery.ToString();
        }
    }
}
